package com.action;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bean.DotBean;
import com.bean.UserBean;
import com.dao.BorrowDotDao;
import com.dao.UserDao;
import com.exception.BorrowDotException;
import com.exception.DBException;
import com.exception.UserException;
import com.google.gson.Gson;
import com.util.HandleInfo;
import com.util.StateInfo;

public class BorrowDotAction
{

	private void BEAN_JSON_SEND(HttpServletResponse response, DotBean dotBean)
	{
		Gson gson = new Gson();
		String json = gson.toJson(dotBean);
		response.setContentType("application/json");
		try
		{
			Writer w = response.getWriter();
			w.write(json);
			w.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
	}
	
	public void getUser(HttpServletRequest request,
			HttpServletResponse response, DotBean dotBean) throws DBException,
			UserException, BorrowDotException
	{
		UserDao userDao = new UserDao();
		UserBean userBean = new UserBean();
		userBean.setUserID(dotBean.getUserID());
		if (!userDao.ifUserExist(userBean))
		{
			throw new UserException("user is not exist");
		}
		else
		{
			BorrowDotDao bdd = new BorrowDotDao();
			bdd.getProvisional(dotBean);
			this.BEAN_JSON_SEND(response, dotBean);
		}
	}

	public void updateUserDot(HttpServletRequest request,
			HttpServletResponse response, DotBean dotBean) throws DBException,
			BorrowDotException, UserException
	{
		
		UserDao userDao = new UserDao();
		UserBean userBean = new UserBean();
		userBean.setUserID(dotBean.getUserID());
		if (!userDao.ifUserExist(userBean))
		{
			throw new UserException("user is not exist");
		}
		BorrowDotDao bDD = new BorrowDotDao();
		bDD.updateProvisional(dotBean);
		HandleInfo.ajax(response, StateInfo.USER_DOT_SUCCESS);
	}
}
